//cell functions
function cellClick(x, y) {
  if (GLOBAL_CONFIG.currentStatus == SINGLE_CELL) {
    this.classList.toggle('alive')
  } else if (GLOBAL_CONFIG.currentStatus == PATTERN) {
    console.log("drawing pattern")
    drawPattern(getPatternCells(GLOBAL_CONFIG.currentPattern, x, y), 'alive')
  }
}

function cellRightClick(x, y) {
  if (GLOBAL_CONFIG.currentStatus == PATTERN) {
    GLOBAL_CONFIG.currentPattern.rotate()
    drawPattern(getPatternCells(GLOBAL_CONFIG.currentPattern, x, y), 'ghost')
  }
}

function cellMouseOver(x, y) {
  GLOBAL_CONFIG.currentMouse.x = x
  GLOBAL_CONFIG.currentMouse.y = y
  if (GLOBAL_CONFIG.currentStatus == SINGLE_CELL) {
    if (GLOBAL_CONFIG.isMouseDown) {
      this.classList.toggle('alive')
    }
  } else if (GLOBAL_CONFIG.currentStatus == PATTERN) {
    drawPattern(getPatternCells(GLOBAL_CONFIG.currentPattern, x, y), 'ghost')
  }
}

function initGrid() {
  var gameBoard = document.getElementById('gameBoard')
  gameBoard.style.gridTemplateColumns = `repeat(${gridWidth}, ${GLOBAL_CONFIG.cellSize}px)`
  // 初始化网格
  for (var y = 0; y < gridHeight; y++) {
    var row = []
    for (var x = 0; x < gridWidth; x++) {
      var cell = document.createElement('div')
      cell.classList.add('cell')
      cell.addEventListener('click', cellClick.bind(cell, x, y))
      cell.addEventListener('mouseover', cellMouseOver.bind(cell, x, y))
      cell.addEventListener('mouseout', clearGhosts)
      cell.addEventListener('contextmenu', function(event) {
        event.preventDefault()
        cellRightClick(x, y)
      })
      gameBoard.appendChild(cell)
      row.push(cell)
    }
    GLOBAL_CONFIG.cells.push(row)
  }
}
